#ifndef UDPTHREAD_H
#define UDPTHREAD_H

#include <QThread>
#include <QDebug>
#include <QString>
#include <QByteArray>
#include <QUdpSocket>
#include <QSharedPointer>
#include <QNetworkDatagram> // 网络数据包
#include <QMutex>
#include <QWaitCondition>

/**
 * @brief 通信类
 */
class MyUdpThreadWorker : public QObject{
    Q_OBJECT
public:
    MyUdpThreadWorker(QObject* parent = nullptr);
    ~MyUdpThreadWorker();

signals:
    void Sig_receive(QByteArray);
    void Sig_error(QString );

public slots:
    void Slot_setLocalPort(short port);
    void Slot_setDestinationIpPort(const QString& destinationIp,  short port);
    /**
     * @brief 若已经连接再次调用，则会
     */
    void Slot_Connect();
    void Slot_DisConnect();
    int Slot_Send(QByteArray);

public:
    QWaitCondition m_waitCondition;
    QMutex m_mutex;
    bool m_isConnected;

private:
    QString m_localIp;
    QString m_destinationIp;

    short m_localPort;
    short m_destinationPort;

    QSharedPointer<QUdpSocket> m_udpSocket;
    QSharedPointer<QNetworkDatagram> m_netWorkDatagram;
};

class UdpThread : public QThread
{
    Q_OBJECT

public:
    UdpThread(QObject* parent = nullptr);
    ~UdpThread();

    void SetLocalPort(short port);
    void SetDestinationIpPort(const QString& destinationIp,  short port);
    bool Connect();
    bool DisConnect();
    int SendData(QByteArray);

signals:
    void Sig_receive(QByteArray);
    void Sig_setLocalPort(short port);
    void Sig_setDestinationIpPort(const QString& destinationIp,  short port);
    void sig_connect();
    void Sig_disConnect();
    void Sig_errorCur(QString);
    void Sig_send(QByteArray);

protected:
    /**
     * @brief 开启线程通信，若已经存在线程正在开启则无响应
     */
    bool startThread();
    /**
     * @brief 关闭线程通信，若无线程则无响应
     */
    bool stopThread();

private:
    MyUdpThreadWorker* m_worker;
    QThread* m_workThread;
};
#endif // UDPTHREAD_H
